package com.sz.controller;


import com.sz.model.BankCard;
import com.sz.model.BankParticulars;
import com.sz.model.Result;
import com.sz.myinterface.SMSCode;
import com.sz.service.IregCardService;
import com.sz.utils.CodeUtils;
import com.sz.utils.Md5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/card")
public class regCardController {

    @Autowired
    private IregCardService iregCardService;

    @Autowired
    private CodeUtils codeUtil;

    @Autowired
    private Md5Util md5Util;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @RequestMapping("/sendNew") // 发送短信验证，并将验证码存到redis
    public String sendNews(String mobile) {
        String sc = SMSCode.sendSMS(mobile);
        redisTemplate.opsForValue().set("checkCode", sc,1, TimeUnit.MINUTES);
        System.out.println("sc = " + sc);
        return sc;
    }

    @RequestMapping("/checkCode")
    public Result checkCode(String number, String code, String telephone, String password) {
        //System.out.println("name = " + name);
        System.out.println("number = " + number);
        System.out.println("code = " + code);
        System.out.println("telephone = " + telephone);
        System.out.println("password = " + password);
        Result result=null;

        String checkCode = redisTemplate.opsForValue().get("checkCode");
        String card = iregCardService.getCard(number, telephone);

        if (checkCode!=null&&!checkCode.equals(code)) {
            return result=new Result(301,"验证码错误或者已过期");
        }
        if (card==null||card == ""){
            return result=new Result(302,"开户失败,用户不存在");
        }

        String card1 = iregCardService.getCard(number, telephone);

        int i=0;
        BankCard bankCard=null;
        if(card1!=null&&telephone!=null&&telephone!=""){
            bankCard = new BankCard(Integer.parseInt(card1), codeUtil.getBankCard(),
                    (long)0, "1", (long)50000, md5Util.getSaltMD5(password));
            i = iregCardService.addCard(bankCard);
            Integer bankId = bankCard.getPkBankId();
            System.out.println("bankId ========= " + bankId);
            iregCardService.addBankParticulars(new BankParticulars(bankId,3,1,1));

        }


        if(i==1){
            result=new Result(200,"开户成功",bankCard);
        }else{
            result=new Result(304,"开户失败，发送异常",bankCard);
        }

        return result;
    }
}
